import { observable, action, toJS } from 'mobx';
import RevisionCk from './RevisionCk';
import TagUtil from "../../util/ckextraTagUtil"
import EditorUtil from '../../util/ckextraEditorUtil';
import Postil from '../../components/ckextra/Postil';

// 默认给的10个明显的颜色
const defaultColors = ['#FF0088', '#FF7744', '#0066FF', '#9955FF', '#DDAA00', '#0064B3', '#177E00', '#6C007E', '#008B8D', '#A500CC'];

export default class Revision {
  @observable show = false;
  showRevise = false;//是否显示修订，用于记录外部传过来的显示修订的值。
  revisionCk = new RevisionCk(this);
  @observable list = [];//显示的列表，对应revisionItem的元素
  // @observable revisionNum = 0;
  @observable chooseItemId = -1;//所选修订元素
  @observable avtiveRevisionParams = {}; // 激活的修订悬浮框的内容
  @observable colorMap = {}; // 不同用户对应不同的颜色

  @action
  setState = (state) => {
    for (let key in state) {
      this[key] = state[key];
    }
  }

  init = () => {
    this.revisionCk.addCKListener();
    this.refresh();
  }

  @action.bound
  choose = (id) => {
    this.chooseItemId = id;
    this.revisionCk.choose(id);
  }

  refreshChooseStatus = () => {
    let item = this.revisionCk.chooseCurrentRevisionNode();
    this.chooseItemId = item ? item.id : -1;
  }

  findNextWithNotFocus = () =>{
    if (!this.list || this.list.length === 0) return;
    let item = this.revisionCk.findNext();
    let nextItemId = item && item.id ? item.id : this.list[0].id;
    return nextItemId;
  }
  findNext = () => {
    // if (!this.list || this.list.length === 0) return;
    // let item = this.revisionCk.findNext();
    // this.chooseItemId = item && item.id ? item.id : this.list[0].id;
    this.chooseItemId = this.findNextWithNotFocus();
    this.revisionCk.choose(this.chooseItemId);
  }

  findPrevious = () => {
    if (!this.list || this.list.length === 0) return;
    let item = this.revisionCk.findPrevious();
    this.chooseItemId = item && item.id ? item.id : this.list[this.list.length - 1].id;
    this.revisionCk.choose(this.chooseItemId);
  }

  receiveAll = () => {
    this.refresh();
    let list = toJS(this.list);
    Array.isArray(list) && list.forEach((item) => this.revisionCk.receive(item.id) );
    this.list = [];
    this.focusEditor();
    // 同时刷新右侧批注信息
    Postil.getCurrentStore().refreshPostil();

    //如果P标签没有内容，增加br标签
    TagUtil.setBrInNullPtag();
  }

  receive = (moveToNext) => {
    let shouldReceive = typeof(this.chooseItemId) === 'number' && this.chooseItemId >= 0;
    if (!shouldReceive) {
      let result = this.revisionCk.chooseCurrentRevisionNode();
      if (result) {
        this.choose(result.id);
        shouldReceive = true;
      } else {
        this.findNext();
      }
    }
    if (shouldReceive) {
      //解决接收修订并移到下一条，光标定位不对的问题
      //先记录下一个修订的ID
      let nextItemId = -1;
      if(moveToNext) nextItemId=this.findNextWithNotFocus();
      
      this.revisionCk.receive(this.chooseItemId);
      this.list = this.list.filter((item) => item.id !== this.chooseItemId );
      this.chooseItemId = -1;
      // moveToNext && this.findNext();
      if (moveToNext) { // 接受并移到下一处，不需要获得焦点
        //this.findNext();
        this.chooseItemId = nextItemId;
        this.revisionCk.choose(this.chooseItemId);
      } else {
        this.focusEditor();
      }
      // 同时刷新右侧批注信息
      Postil.getCurrentStore().refreshPostil();
    }
  }

  rejectAll = () => {
    this.refresh();
    let list = toJS(this.list);
    Array.isArray(list) && list.forEach((item) => this.revisionCk.reject(item.id) );
    this.list = [];
    this.focusEditor();
    // 拒绝修订之后刷新批注信息
    Postil.getCurrentStore().refreshPostil();

    //如果P标签没有内容，增加br标签
    TagUtil.setBrInNullPtag();
  }

  reject = (moveToNext) => {
    let shouldReject = typeof(this.chooseItemId) === 'number' && this.chooseItemId >= 0;
    if (!shouldReject) {
      let result = this.revisionCk.chooseCurrentRevisionNode();
      if (result) {
        this.choose(result.id);
        shouldReject = true;
      } else {
        this.findNext();
      }
    }
    if (shouldReject) {

      //解决接收修订并移到下一条，光标定位不对的问题
      //先记录下一个修订的ID
      let nextItemId = -1;
      if(moveToNext) nextItemId=this.findNextWithNotFocus();

      this.revisionCk.reject(this.chooseItemId);
      this.list = this.list.filter((item) => item.id !== this.chooseItemId );
      this.chooseItemId = -1;
      // moveToNext && this.findNext();
      if (moveToNext) { // 拒绝并移到下一处，不需要获得焦点
        //this.findNext();
        this.chooseItemId = nextItemId;
        this.revisionCk.choose(this.chooseItemId);
      } else {
        this.focusEditor();
      }
      // 拒绝修订之后刷新批注信息
      Postil.getCurrentStore().refreshPostil();
    }
  }

  // 获得ckEditor焦点 fix: 接受拒绝后ctrl+z无效 (编辑器插入U, 获得焦点)
  focusEditor = () => {
    const editor = EditorUtil.getEditor();
    editor.focusManager.lock();

    editor.focus();
    // fix: 修订模式，接受拒绝修订后，获得焦点光标是黑色的 (此时获得焦点是不需要save的)
    if(EditorUtil.getRanges() && EditorUtil.getRanges()[0]){
      const {startOffset,endOffset,startContainer,endContainer} = EditorUtil.getRanges()[0];
      if(startOffset === endOffset && startContainer.equals(endContainer)){
        TagUtil.insertTempUtag('',this, true);
      }
    }
    this.avtiveRevisionParams = {};

    setTimeout(() => {
      editor.focusManager.unlock();
    }, 0);
  }

  showReviseList = (show) => {
    this.showRevise = !!show;
    this.show = this.showRevise || this.revisionCk.shouldRevise;
    this.revisionCk.showRevising(this.show);
    this.refresh();
  }

  toggleRevising = (show) => {
    this.revisionCk.toggleRevising(show);
    this.show = this.showRevise || this.revisionCk.shouldRevise;
    this.revisionCk.showRevising(this.show);
    this.refresh();
  }

  // 生成随机的颜色 - 用户人数超过defaultColors的长度之后使用（一般不会超出）
  getRandomColor = () => {
    const r = Math.floor(Math.random()*256).toString(16);
    const g = Math.floor(Math.random()*256).toString(16);
    const b = Math.floor(Math.random()*256).toString(16);
    const changeC = (c) => {
      if (c.length === 1) {
        return `${c}0`;
      }
      return c;
    }
    const randomColor = `#${changeC(r)}${changeC(g)}${changeC(b)}`;
    return randomColor;
  }

  refresh = () => {
    // fix: 选中当前修订的时候也会记录一次: 先锁上，再解锁
    const editor = EditorUtil.getEditor();
    editor.focusManager.lock();

    let list = [];
    // this.list = this.revisionCk.getAllItems().filter((item) => item.id !== -1 && item.text);
    this.revisionCk.getAllItems().map(item => {
      if (item.id !== -1 && item.text) {
        if (item.type === 'I' || item.type === 'D') {
          // 不同的author对应不同颜色的u标签: 
          //当前操作人默认#cc3300，不需要再设置
          //其他的取defaultColors的颜色,超过defaultColors长度就随机生成
          if (item.author !== CKEditorParams.author) {
            if (!this.colorMap[item.author]) {
              const len = Object.keys(this.colorMap).length;
              this.colorMap[item.author] = defaultColors[len] || this.getRandomColor();
            }
            item.node.$.setAttribute('style', `color: ${this.colorMap[item.author]}`);
          }

          // fix: 开启修订后，修订的内容无人员及时间显示
          item.node.$.onmouseover = (e) => {
            this.avtiveRevisionParams = {
              e: e,
              xiudingren: item.author,
              xiudingshijian: item.datetime,
              typeText: item.type === 'I' ? '插入内容' : '删除内容',
              content: item.text || '',
            };
          };
          item.node.$.onmouseout = () => {
            this.avtiveRevisionParams = {};
          };
        }
        list.push(item);
      }
    });
    this.list = list;
    // 同时刷新右侧批注信息
    Postil.getCurrentStore().refreshPostil();

    // 不同的author对应不同颜色的u标签: 当前操作人取#cc3300，其他的取defaultColors的颜色,超过defaultColors长度就随机生成
    // if (iframeDocument) {
    //   const UTags = iframeDocument && iframeDocument.getElementsByTagName("body")[0].getElementsByTagName("u");
    //   for(let i = 0; i < UTags.length; i++){
    //     const tagAuthor = UTags[i].attributes.xiudingren.value;
    //     if (!this.colorMap[tagAuthor]) {
    //       const colorMapLen = Object.keys(this.colorMap).length;
    //       if (tagAuthor === CKEditorParams.author) { // 当前操作人的默认颜色是#cc3300
    //         this.colorMap[tagAuthor] = '#cc3300';
    //       } else if (colorMapLen <= defaultColors.length) {
    //         this.colorMap[tagAuthor] = defaultColors[colorMapLen - 1];
    //       } else {
    //         this.colorMap[tagAuthor] = this.getRandomColor();
    //       }
    //     }
    //     UTags[i].setAttribute('style', `color: ${this.colorMap[tagAuthor]}`);
    //   }
    // }

    setTimeout(() => {
      editor.focusManager.unlock();
    }, 0);
  }

  mergeItem = (item) =>{
    if (!item) return;
    if (item.id === -1) item.id = this.generateId();
    let index = this.list.findIndex(o=>item.id === o.id);
    if (index >= 0 ){
      this.list[index] = item;
    } else {
      this.list.push(item);
    }
    return item.id;
  }
  
  generateId = () => {
    if (!this.list || !this.list.length) {
      return 0;
    }
    let list = [...this.list].sort((first, second) => {
      return parseInt(first.id || 0) - parseInt(second.id || 0);
    });
    return parseInt(list[list.length - 1].id || 0) + 1;
  }

  getRevisionData = () => {
    return toJS(this.list);
  }
  clearChooseItemId = () => {
    this.chooseItemId = -1;
  }

  @action
  clearAvtiveRevisionParams = () => {
    this.avtiveRevisionParams = {};
  }
}